package com.kancy.publicapi.common.util;

import com.kancy.publicapi.common.properties.IpProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author kancy
 * @date 2019/12/6 23:21
 **/
public class IPUtils {

    public static String getRequestIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if("0:0:0:0:0:0:0:1".equals(ip) || "127.0.0.1".equals(ip)){
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (Exception e) {
                ip = request.getRemoteAddr();
            }
        }
        return ip;
    }

    private static String localIp = "";
    /**
     * 实现ip转换（内外切换到外网）
     * @return
     */
    public static String getIp() {
        if (StringUtils.isEmpty(localIp)){
            synchronized (localIp){
                if (StringUtils.isEmpty(localIp)){
                    String ip = getLocalIp();
                    ApplicationContext context = SpringUtils.getContext();
                    if (context!=null){
                        IpProperties ipProperties = context.getBean(IpProperties.class);
                        if (ipProperties!=null && !CollectionUtils.isEmpty(ipProperties.getMapping())){
                            localIp = ipProperties.getMapping().getOrDefault(ip, ip);
                        }
                    }
                    if (StringUtils.isEmpty(localIp)){
                        localIp = ip;
                    }
                }
            }
        }
        return localIp;
    }

    public static String getLocalIp() {
        InetAddress ip = null;
        try {
            Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
            while(netInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface)netInterfaces.nextElement();
                Enumeration ips = ni.getInetAddresses();
                while(ips.hasMoreElements()) {
                    ip = (InetAddress)ips.nextElement();
                    if (ip != null && !"".equals(ip)) {
                        String sIP = ip.getHostAddress();
                        if (sIP != null && sIP.indexOf(":") <= -1 && !"127.0.0.1".equals(sIP)) {
                            String displayName = ni.getDisplayName();
                            if (displayName!=null && displayName.contains("Virtual")){
                                continue;
                            }
                            if (sIP.endsWith(".1")){
                                continue;
                            }
                            return sIP;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "127.0.0.1";
    }
}
